/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.rabbit.core.http11;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import com.rabbit.constants.Constants;

/**
 * @author gogole_09
 * 
 */
public class DefaultHttpResponse implements HttpResponse {

	private static final int BUFFER_SIZE = 1024;
	private OutputStream outputStream;
	private HttpRequest httpRequest;

	/**
	 * @param outputStream
	 */
	public DefaultHttpResponse(OutputStream outputStream, HttpRequest request) {
		this.outputStream = outputStream;
		this.httpRequest = request;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.rabbit.core.http11.HttpResponse#sendRedicrt()
	 */
	@Override
	public void sendRedicrt() {
		byte[] buff = new byte[BUFFER_SIZE];
		FileInputStream inputStream = null;
		try {
			File file = new File(Constants.RABBIT_WEBROOT, httpRequest.getUri());
			if (!file.exists()) {
				file = new File(Constants.RABBIT_WEBROOT, "/404.htm");
			}
			inputStream = new FileInputStream(file);
			int ch = inputStream.read(buff, 0, BUFFER_SIZE);
			while (ch != -1) {
				outputStream.write(buff, 0, ch);
				ch = inputStream.read(buff, 0, BUFFER_SIZE);
			}
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			try {
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	/**
	 * @return the httpRequest
	 */
	public HttpRequest getHttpRequest() {
		return httpRequest;
	}

	/**
	 * @param httpRequest
	 *            the httpRequest to set
	 */
	public void setHttpRequest(HttpRequest httpRequest) {
		this.httpRequest = httpRequest;
	}

}
